package com.digital.herbarium.Entity;
import cn.hutool.core.util.StrUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;


//声明是个切面的类
@Aspect
//交给spring管理
@Component
public class CheckTokenAspect {

    /**
     * @Pointct 表示该方法可用于 com.digital.herbarium.annotation.CheckToken 这个注解
     * 还可以使用*号表示通配符
     */
    @Pointcut("@annotation(com.digital.herbarium.annotation.CheckToken)")
    public void pointcut() {

    }

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Around("pointcut()")
    public Object checkTokenAroundAspect(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取请求头
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        //从请求头中获取需要的参数
        String token = request.getHeader("Authorization");

        if (StrUtil.hasEmpty(token) || StrUtil.hasBlank(token)) {
            //controller 上面的方法的返回值类型要和这里一样
            return ResponseResult.TOKEN_FAILED().setData("token验证失败");
        }
        //验证token是否有效
        boolean validate = jwtTokenUtil.validateToken(token);
        if (validate){
            return ResponseResult.TOKEN_FAILED().setData("token验证失败");
        }
        //结束，继续执行方法逻辑
        return joinPoint.proceed();
    }

}